<?php

namespace app\api\controller;

use app\api\model\ActivitySignup as mActivitySignup;
use app\api\model\Activity as mActivity;
use app\common\controller\Api;
use think\captcha\Captcha;
use think\Config;

/**
 * 活动接口
 */
class Activity extends Api
{
    protected $noNeedLogin = ['list','details'];

    /**
     * 活动列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function list()
    {
        $list=(new mActivity())->order('weigh desc')->paginate(10);
        $this->success('',$list);
    }

    /**
     * 活动详情
     * @return void
     * @throws \think\exception\DbException
     */
    public function details()
    {
        $id = request()->param('id');
        $data['find']=(new mActivity())->get($id);
        $count= (new mActivitySignup())->where(['activity_id'=>$id])->count();
        $data['already_num']=$count;


        $status=1;
        if($data['find']['num']<=$count){
            $status=0;
        }
        if($data['find']['enroll_time']<time()){
            $status=0;
        }

        $data['find']['status']=$status;
        $this->success('',$data);
    }

    /**
     * 提交报名
     * @return void
     */
    public function signUp(){
        $param = request()->param();
        $captcha = new Captcha();
        $is_code=$captcha->check($param['code'],'');
        if(!$is_code){
            $this->error('验证码错误');
        }
        $find=(new mActivity())->get($param['activity_id']);
        $count= (new mActivitySignup())->where(['activity_id'=>$param['activity_id']])->count();
        if($find['num']<$count+1){
            $this->error('人员已满');
        }
        if($find['enroll_time']<time()){
            $this->error('报名时间已过');
        }
        //判断时间 是否到期
        $user = $this->auth;
//        $user->id=1;
        $where_find['activity_id']=$param['activity_id'];
        $where_find['user_id']=$user->id;
        $is_find=(new mActivitySignup())->where($where_find)->find();
        if(!empty($is_find)){
            $this->error('您已提交此报名');
        }

        $save['user_id']=$user->id;
        $save['activity_id']=$param['activity_id'];
        $save['name']=$param['name'];
        $save['phone']=$param['phone'];
        $save['id_num']=$param['id_num'];
        $save['remarks']=$param['remarks'];
        $save['createtime']=time();
        (new mActivitySignup())->save($save);
        $this->success('');
    }
    public function ListLog()
    {
        $user = $this->auth;
        $where['user_id']=$user->id;
        $list=(new mActivitySignup())->where($where)->order('id desc')->paginate()->each(function($item,$key){
            $activity=(new mActivity())->get($item['activity_id']);
            $item['activity']=$activity;
            return $item;
        });
        $this->success('',$list);
    }
}